package cd.cdyb.sms.service.impl;

import cd.cdyb.sms.dao.CompanyDao;
import cd.cdyb.sms.dao.EmployeeDao;
import cd.cdyb.sms.dao.SystemConfigDao;
import cd.cdyb.sms.domain.Company;
import cd.cdyb.sms.domain.Employee;
import cd.cdyb.sms.domain.SystemConfig;
import cd.cdyb.sms.dto.PageResult;
import cd.cdyb.sms.dto.SmsExcessDto;
import cd.cdyb.sms.dto.expand.ExCompanyDto;
import cd.cdyb.sms.dto.query.CompanyQueryDto;
import cd.cdyb.sms.exception.BusinessException;
import cd.cdyb.sms.service.CompanyService;
import cd.cdyb.sms.service.RedisService;
import cd.cdyb.sms.utils.BeanUtilPlus;
import cd.cdyb.sms.utils.CacheUtils;
import cd.cdyb.sms.utils.MD5Util;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lin
 * @since 2024-05-14
 */
@Service
public class CompanyServiceImpl implements CompanyService {

    @Resource
    private CompanyDao companyDao;

    @Resource
    private EmployeeDao employeeDao;

    @Resource
    private RedisService redisService;
    @Resource
    private SystemConfigDao systemConfigDao;

    @Override
    public void insertCompany(ExCompanyDto exCompanyDto) throws BusinessException {

        String phone = exCompanyDto.getPhone();
        LambdaQueryWrapper<Company> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Company::getPhone, phone);
        Integer count = companyDao.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException("该公司手机号已存在");
        }
        Company company = BeanUtilPlus.copyAs(exCompanyDto, Company.class);
        String companyKey = IdUtil.getSnowflake().nextIdStr();
        String companySecret = IdUtil.fastUUID();

        company.setCompanyKey(companyKey);
        company.setCompanySecret(companySecret);
        companyDao.insert(company);

        Employee employee = new Employee();
        employee.setCompanyId(company.getCompanyId());
        employee.setUsername(company.getPhone());
        employee.setPhone(company.getPhone());
        employee.setCompanyName(company.getCompanyName());
        String pwd = MD5Util.MD5Encode("4321", "UTF-8");
        employee.setPassword(pwd);
        employeeDao.insert(employee);


    }


    @Override
    public void updateCompany(ExCompanyDto exCompanyDto) throws BusinessException {
        Integer companyId = exCompanyDto.getCompanyId();
        Company oldCompany = companyDao.selectById(companyId);

        //判断新手机号是否已存在
        if (!oldCompany.getPhone().equals(exCompanyDto.getPhone())) {
            String phone = exCompanyDto.getPhone();
            LambdaQueryWrapper<Company> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Company::getPhone, phone);
            Integer count = companyDao.selectCount(wrapper);
            if (count > 0) {
                throw new BusinessException("该公司手机号已存在");
            }
        }

        oldCompany.setCompanyName(exCompanyDto.getCompanyName());
        oldCompany.setCreditCode(exCompanyDto.getCreditCode());
        oldCompany.setIndustryFee(exCompanyDto.getIndustryFee());
        oldCompany.setMarketingFee(exCompanyDto.getMarketingFee());
        oldCompany.setEmail(exCompanyDto.getEmail());
        oldCompany.setLicense(exCompanyDto.getLicense());
        oldCompany.setIndustryPrompt(exCompanyDto.getIndustryPrompt());
        oldCompany.setMarketingPrompt(exCompanyDto.getMarketingPrompt());
        oldCompany.setPhone(exCompanyDto.getPhone());
        oldCompany.setMinuteLimit(exCompanyDto.getMinuteLimit());
        oldCompany.setHourLimit(exCompanyDto.getHourLimit());
        oldCompany.setDayLimit(exCompanyDto.getDayLimit());
        companyDao.updateById(oldCompany);


        //更新关联的用户
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getCompanyId, companyId);
        Employee employee = employeeDao.selectOne(wrapper);
        employee.setCompanyName(exCompanyDto.getCompanyName());
        employee.setPhone(exCompanyDto.getPhone());
        employeeDao.updateById(employee);

        redisService.removeKey(CacheUtils.CacheName.COMPANY_INFO_KEY, oldCompany.getCompanyKey());

    }

    @Override
    public PageResult<ExCompanyDto> findCompanyPage(CompanyQueryDto companyQueryDto) {
        Page<Company> page = new Page<>(companyQueryDto.getPageNo(), companyQueryDto.getPageSize());
        IPage<ExCompanyDto> iPage = companyDao.findCompanyPage(companyQueryDto, page);
        return new PageResult<>(companyQueryDto.getPageNo(), companyQueryDto.getPageSize(), iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public ExCompanyDto getCompanyById(Integer companyId) {
        Company company = companyDao.selectById(companyId);
        return BeanUtilPlus.copyAs(company, ExCompanyDto.class);
    }

    @Override
    public SmsExcessDto getSmsExcessWithClient(Integer companyId) {
        Company company = companyDao.selectById(companyId);
        SmsExcessDto companyDto = new SmsExcessDto();
        companyDto.setIndustryCount(0);
        companyDto.setMarketingCount(0);
        companyDto.setType(0);
        if (Objects.nonNull(company)) {
            companyDto.setIndustryCount(company.getIndustryCount());
            companyDto.setMarketingCount(company.getMarketingCount());
        }
        return companyDto;
    }

    @Override
    public List<SmsExcessDto> getSmsExcessWithAdmin() {
        List<Company> selectList = companyDao.selectList(new LambdaQueryWrapper<>());
        List<SmsExcessDto> smsExcessDtoList = selectList.stream()
                .map(company -> new SmsExcessDto(company.getIndustryCount(), company.getMarketingCount(), 0, company.getCompanyName(), company.getCompanyId()))
                .collect(Collectors.toList());
        SystemConfig systemConfig = systemConfigDao.selectOne(null);

        SmsExcessDto admin = new SmsExcessDto(systemConfig.getIndustryCount(), systemConfig.getMarketingCount(), 1, "admin", 0);
        smsExcessDtoList.add(admin);
        return smsExcessDtoList.stream().sorted((o1, o2) -> o2.getType().compareTo(o1.getType())).collect(Collectors.toList());
    }

    @Override
    public ExCompanyDto getCacheCompanyByKey(String companyKey) {
        Object o = redisService.vGet(CacheUtils.CacheName.COMPANY_INFO_KEY, companyKey);
        if (o == null) {
            Company companyByCompanyKey = companyDao.getCompanyByCompanyKey(companyKey);
            ExCompanyDto exCompanyDto = BeanUtilPlus.copyAs(companyByCompanyKey, ExCompanyDto.class);
            redisService.vPut(CacheUtils.CacheName.COMPANY_INFO_KEY, companyKey, exCompanyDto);
            return exCompanyDto;
        }
        return (ExCompanyDto) o;
    }

    @Override
    public ExCompanyDto getCompanyByKey(String companyKey) {
        Company companyByCompanyKey = companyDao.getCompanyByCompanyKey(companyKey);
        ExCompanyDto exCompanyDto = BeanUtilPlus.copyAs(companyByCompanyKey, ExCompanyDto.class);
        return exCompanyDto;
    }

    @Override
    public List<ExCompanyDto> findCompanyList() {
        List<Company> companyList = companyDao.selectList(new LambdaQueryWrapper<>());
        return BeanUtilPlus.copyAs(companyList, ExCompanyDto.class);
    }
}
